package com.ericsson.nfc.signing.bc.crypto.signers;

import java.math.BigInteger;
import java.util.Enumeration;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERSequence;

/**
 * http://www.ipa.go.jp/security/rfc/RFC3279EN.html#223
 * 
 * The Ecdsa-Sig-Value object.
 * <pre>
 *      Ecdsa-Sig-Value ::= SEQUENCE {
        r INTEGER,
        s INTEGER }
 * </pre>
 */
public class EcdsaSigValue
    extends ASN1Encodable
{
    private BigInteger              r;
    private BigInteger              s;

    public static EcdsaSigValue getInstance(
        ASN1TaggedObject obj,
        boolean          explicit)
    {
        return getInstance(ASN1Sequence.getInstance(obj, explicit));
    }

    public static EcdsaSigValue getInstance(
        Object  obj)
    {
        if (obj instanceof EcdsaSigValue)
        {
            return (EcdsaSigValue)obj;
        }
        else if (obj instanceof ASN1Sequence)
        {
            return new EcdsaSigValue((ASN1Sequence)obj);
        }

        throw new IllegalArgumentException("unknown object in factory: " + obj.getClass().getName());
    }

    public EcdsaSigValue(
        BigInteger r,
        BigInteger s)
    {
        this.r = r;
        this.s = s;
    }

    public EcdsaSigValue(
        ASN1Sequence  obj)
    {
        Enumeration             e = obj.getObjects();

        r = DERInteger.getInstance(e.nextElement()).getValue();
        s = DERInteger.getInstance(e.nextElement()).getValue();
    }

    public BigInteger getR() {
        return r;
    }

    public BigInteger getS() {
        return s;
    }

    public DERObject toASN1Object()
    {
        ASN1EncodableVector  v = new ASN1EncodableVector();

        v.add(new DERInteger(r));
        v.add(new DERInteger(s));

        return new DERSequence(v);
    }
}
